/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;
import data.Recipient;

/**
 *
 * @author Cody
 */
import java.net.*;
import java.util.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class RecipientServer
{
public static void main(String [] args)
{
    Connection connection = null;  
    Statement stat = null;
    ResultSet result = null;
    
    String sql;
    
    
    Socket incoming;
    try
    {
    ServerSocket s = new ServerSocket(8190); //the server socket
    System.out.println("Recipient sever listening on port 8190");
    while(true) //put in a loop that keeps running
    {
        incoming = s.accept(); //accept a connection from a client
        Scanner in = null;
        PrintWriter out = null;

        try
        {   
            //Read in two lies, one as username and one as recipient
            //The recipients username
            System.out.println("Incoming..");
            InputStream inStream = incoming.getInputStream(); // the INPUT stream handler
            
            in = new Scanner(inStream); //setup of input
            
            String username = in.nextLine();
            System.out.println(username);
            String recipientUsername = in.nextLine();
            System.out.println(recipientUsername);
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Incoming..");
            connection = DriverManager.getConnection("jdbc:mysql://LOCALHOST/FileTransfer","root","root");
                    System.out.println("Incoming..");
            stat = connection.createStatement();
                    sql = "INSERT INTO recipients (username, recipient) VALUES ('"+ username +"','"+ recipientUsername+"');";
                    stat.execute(sql);
            
            out = new PrintWriter(incoming.getOutputStream(), true);
            out.println("success");   
        }
        catch(Exception e){
            System.out.println(e);
            out = new PrintWriter(incoming.getOutputStream(), true);
            out.println("fail"); 
        }
        finally
        {
            out.close();
            in.close();
            incoming.close();
        }
        
    }
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
    
    }
}
